package jmine.tec.environment.db;

import java.net.URL;

import jmine.tec.environment.EnvironmentException;
import jmine.tec.environment.EnvironmentMessages;
import bancosys.tec.utils.db.descriptor.ReferenceDatabaseEntry;

/**
 * Loads SQL entries
 * 
 * @author lundberg
 */
public class SQLPostscriptEntryLoader implements PostscriptEntryLoader {

    /**
     * {@inheritDoc}
     */
    public boolean load(DBEnvironment environment, ReferenceDatabaseEntry entry) {
        if (entry.getType().equalsIgnoreCase("sql")) {
            this.executaSQL(environment, entry.getClasspathResourcePath());
            return true;
        } else {
            return false;
        }
    }

    /**
     * Executa um arquivo com SQL.
     * 
     * @param environment environment
     * @param fileName file name.
     */
    private void executaSQL(DBEnvironment environment, String fileName) {
        URL url = this.getClass().getClassLoader().getResource(fileName);
        if (url == null) {
            throw new EnvironmentException(EnvironmentMessages.FILE_NOT_FOUND.create(fileName));
        }
        try {
            DBLoadedServerUtils helper = environment.getHelper();
            helper.initConnection();
            helper.executeFile(url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
